package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.mapper.SysOperLogMapper;
import com.ruoyi.system.service.ISysOperLogService;

/**
 * 操作日志 服务层处理
 *
 * @author ruoyi
 */
@Service
public class SysOperLogServiceImpl implements ISysOperLogService {
    @Autowired
    private SysOperLogMapper operLogMapper;

    /**
     * 新增操作日志菜单
     *
     * @param operLog 操作日志对象
     */
    @Override
    public void insertOperlog(SysOperLog operLog) {
        operLogMapper.insertOperlog(operLog);
    }

    /**
     * 查询系统操作日志集合
     *
     * @param operLog 操作日志对象
     * @return 操作日志集合
     */
    @Override
    public List<SysOperLog> selectOperLogList(SysOperLog operLog) {
        List<SysOperLog> sysOperLogs = operLogMapper.selectOperLogList(operLog);
        for (SysOperLog sysOperLog : sysOperLogs) {
            if (StringUtils.isNoneBlank(sysOperLog.getTraceSpanId())) {
                int i = operLogMapper.selCountByParentSpanId(sysOperLog.getTraceSpanId());
                sysOperLog.setTraceCount(i);
            }
        }

        return sysOperLogs;
    }


    @Override
    public List<SysOperLog> selListByParentSpanId(String parentSpanId) {
        List<SysOperLog> result = new ArrayList<>();
        // 获取直接子节点
        List<SysOperLog> directChildren = operLogMapper.selectByParentSpanId(parentSpanId);

        // 递归获取所有子孙节点
        getAllDescendants(directChildren, result);

        return result;
    }

    private void getAllDescendants(List<SysOperLog> currentLevel, List<SysOperLog> result) {
        if (currentLevel == null || currentLevel.isEmpty()) {
            return;
        }

        // 将当前层级添加到结果中
        result.addAll(currentLevel);

        // 获取下一层级
        for (SysOperLog log : currentLevel) {
            List<SysOperLog> nextLevel = operLogMapper.selectByParentSpanId(log.getTraceSpanId());
            if (nextLevel != null && !nextLevel.isEmpty()) {
                getAllDescendants(nextLevel, result);
            }
        }
    }




    /**
     * 批量删除系统操作日志
     *
     * @param operIds 需要删除的操作日志ID
     * @return 结果
     */
    @Override
    public int deleteOperLogByIds(Long[] operIds) {
        return operLogMapper.deleteOperLogByIds(operIds);
    }

    /**
     * 查询操作日志详细
     *
     * @param operId 操作ID
     * @return 操作日志对象
     */
    @Override
    public SysOperLog selectOperLogById(Long operId) {
        return operLogMapper.selectOperLogById(operId);
    }

    /**
     * 清空操作日志
     */
    @Override
    public void cleanOperLog() {
        operLogMapper.cleanOperLog();
    }



}
